package com.lanou.utp.utils.utilsImpl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lanou.utp.entity.LoginUser;
import com.lanou.utp.entity.ValidateDetails;
import com.lanou.utp.utils.TokenManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtManager implements TokenManager {

    @Value("${com.lanou.token.jwt-secret}")
    private String JWT_SECRET;

    @Value("${com.lanou.token.expire-time-seconds}")
    private Long EXPIRE_TIME_SECONDS;

    @Override
    public String createLoginToken(ValidateDetails user) {
        Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
        Date expireTime = new Date(System.currentTimeMillis() + EXPIRE_TIME_SECONDS * 1000);
        String token = JWT.create()
                .withClaim("id", user.getId())
                .withClaim("name", user.getName())
                .withClaim("cnl", user.getChannel())
                .withClaim("pst", user.getPosition())
                .withClaim("dur", EXPIRE_TIME_SECONDS)
                .withExpiresAt(expireTime)
                .sign(algorithm);

        return token;
    }

    @Override
    public LoginUser parseLoginToken(String token) {
        DecodedJWT decode = JWT.decode(token);
        LoginUser user = new LoginUser();
        Integer id = decode.getClaim("id").asInt();
        String name = decode.getClaim("name").asString();
        Integer channel = decode.getClaim("cnl").asInt();
        Integer position = decode.getClaim("pst").asInt();
        Long duration = decode.getClaim("dur").asLong();
        user.setId(id);
        user.setName(name);
        user.setChannel(channel);
        user.setPosition(position);
        return user;
    }
}
